package org.csu.small.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.csu.small.common.Constant;
import org.csu.small.common.UniformResponse;
import org.csu.small.entity.Cart;
import org.csu.small.entity.Favorites;
import org.csu.small.entity.Product;
import org.csu.small.persistence.FavoritesMapper;
import org.csu.small.persistence.ProductMapper;
import org.csu.small.service.IFavoritesService;
import org.csu.small.utils.PropertiesUtil;
import org.csu.small.vo.CartProductVO;
import org.csu.small.vo.CartVO;
import org.csu.small.vo.FavProductVO;
import org.csu.small.vo.FavoritesVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class FavoritesServiceImpl implements IFavoritesService {

    @Autowired
    FavoritesMapper favoritesMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public UniformResponse<FavoritesVO> add(Integer userId, Integer productId){
        Favorites favorites = favoritesMapper.selectOne(Wrappers.<Favorites>query().eq("user_id",userId).eq("product_id",productId));
        int rows = favoritesMapper.selectCount(Wrappers.<Favorites>query().eq("user_id",userId).eq("product_id",productId));
        Product product = productMapper.selectById(productId);
        if(rows != 0){
            favoritesMapper.deleteById(favorites.getId());
            return UniformResponse.createForSuccessMessage("取消收藏成功");
        }else{
            Favorites newfavorites = new Favorites();
            newfavorites.setUserId(userId);
            newfavorites.setProductId(productId);
            newfavorites.setAddPrice(product.getPrice());
            newfavorites.setCreateTime(LocalDateTime.now());
            newfavorites.setUpdateTime(LocalDateTime.now());
            newfavorites.setChecked(1);
            int insertcount = favoritesMapper.insert(newfavorites);
            if (insertcount == 0){
                return UniformResponse.createForErrorMessage("添加失败");
            }
        }
        FavoritesVO favoritesVO = getFavList(userId);
        return UniformResponse.createForSuccess(favoritesVO);
    }

    @Override
    public UniformResponse<FavoritesVO> deleteByProductIds(Integer userId, String productIds) {
        List<String> productIdList = Splitter.on(",").splitToList(productIds);
        if(CollectionUtils.isNotEmpty(productIdList)){
            for(String productId : productIdList){
                Integer iproductId = Integer.valueOf(productId);
                int rows = favoritesMapper.selectCount(Wrappers.<Favorites>query().eq("user_id",userId).eq("product_id",productId));

                if(rows != 0){
                    QueryWrapper<Favorites> query = new QueryWrapper<>();
                    query.eq("user_id",userId).eq("product_id",iproductId);
                    favoritesMapper.delete(query);
                }
            }
        }else {
            return UniformResponse.createForSuccessMessage("请选择商品");
        }
        FavoritesVO favoritesVO = getFavList(userId);
        return UniformResponse.createForSuccess(favoritesVO);
    }

    @Override
    public UniformResponse<FavoritesVO> getFavoritesList(Integer userId) {
        FavoritesVO favoritesVO = getFavList(userId);
        return UniformResponse.createForSuccess(favoritesVO);
    }

    @Override
    public UniformResponse isInFav(Integer userId, String productId) {
        int rows = favoritesMapper.selectCount(Wrappers.<Favorites>query().eq("user_id",userId).eq("product_id",productId));
        if (rows != 0){
            return UniformResponse.createForSuccess(true);
        }else {
            return UniformResponse.createForSuccess(false);
        }
    }

    @Override
    public UniformResponse<FavoritesVO> selectOrUnSelect(Integer userId, Integer productId, Integer status){
        Favorites favorites = favoritesMapper.selectOne(Wrappers.<Favorites>query().eq("user_id",userId).eq("product_id",productId));
        int rows = favoritesMapper.selectCount(Wrappers.<Favorites>query().eq("user_id",userId).eq("product_id",productId));
        if(rows != 0){
            favorites.setChecked(status);
            favorites.setUpdateTime(LocalDateTime.now());
            int updatecount = favoritesMapper.updateById(favorites);
            if(updatecount == 0){
                return UniformResponse.createForErrorMessage("选择或取消选择失败");
            }
        }
        FavoritesVO favoritesVO = getFavList(userId);
        return UniformResponse.createForSuccess(favoritesVO);
    }

    @Override
    public UniformResponse<FavoritesVO> selectOrUnSelectAll(Integer userId, Integer status){
        List<Favorites> favoritesList= favoritesMapper.selectList(Wrappers.<Favorites>query().eq("user_id",userId));
        //int rows = cartMapper.selectCount(Wrappers.<Cart>query().eq("user_id",userId));
        if(CollectionUtils.isNotEmpty(favoritesList)){
            for(Favorites favoritesItem : favoritesList){
                favoritesItem.setChecked(status);
                favoritesItem.setUpdateTime(LocalDateTime.now());
                favoritesMapper.updateById(favoritesItem);
            }
        }
        FavoritesVO favoritesVO = getFavList(userId);
        return UniformResponse.createForSuccess(favoritesVO);
    }

    @Override
    public UniformResponse<Integer> getFavCount(Integer userId){
        List<Favorites> favoritesList= favoritesMapper.selectList(Wrappers.<Favorites>query().eq("user_id",userId));
        Integer count = 0;
        if(CollectionUtils.isNotEmpty(favoritesList)){
            count = favoritesList.size();
        }
        return UniformResponse.createForSuccess(count);
    }


    public FavoritesVO getFavList(Integer userId) {
        FavoritesVO favoritesVO = new FavoritesVO();

        //获取该用户的收藏列表
        QueryWrapper<Favorites> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);

        List<Favorites> favoritesList = favoritesMapper.selectList(queryWrapper);

        List<FavProductVO> favProductVOList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(favoritesList)) {
            for (Favorites favItem : favoritesList) {
                FavProductVO favProductVO = new FavProductVO();

                favProductVO.setId(favItem.getId());
                favProductVO.setUserId(favItem.getUserId());
                favProductVO.setProductId(favItem.getProductId());

                Product product = productMapper.selectById(favItem.getProductId());

                if (product != null) {
                    favProductVO.setProductMainImage(product.getMainImage());
                    favProductVO.setProductName(product.getName());
                    favProductVO.setProductSubtitle(product.getSubtitle());
                    favProductVO.setProductStatus(product.getStatus());
                    favProductVO.setProductPrice(product.getPrice());
                    favProductVO.setProductStock(product.getStock());
                    favProductVO.setProductChecked(favItem.getChecked());
                }
                favProductVOList.add(favProductVO);
            }
            favoritesVO.setFavProductVOList(favProductVOList);
            favoritesVO.setAllChecked(this.getAllCheckedStatus(userId));
            favoritesVO.setImageHost(PropertiesUtil.getProperty("image.server.url"));
        }
        return favoritesVO;
    }

    /**
     * 是否全选
     * @param userId
     * @return
     */
    private boolean getAllCheckedStatus(Integer userId){
        if(userId == null){
            return false;
        }
        QueryWrapper<Favorites> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(("user_id"),userId);
        queryWrapper.eq("checked",Constant.Favorites.UN_CHECKED);
        int result = favoritesMapper.selectCount(queryWrapper);
        return result == 0;
    }

}
